package com.hsmw.api.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hsmw.api.config.jwt.CurrentHsmwUserUtils;
import com.hsmw.api.config.jwt.LoginUser;
import com.hsmw.api.controller.pub.TencentPushUtils;
import com.hsmw.api.mapper.*;
import com.hsmw.common.base.BaseService;
import com.hsmw.api.utils.CommonUtils;
import com.htn.common.core.base.DataResponse;
import com.hsmw.domain.*;
import com.htn.common.core.constant.CommonConstants;
import com.htn.common.core.constant.UserTypeEnum;
import com.htn.common.core.enums.ExamineTypeEnum;
import com.htn.common.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;


/**
 * @author WD
 */
@Service
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class HsmwAuditService extends BaseService<HsmwAuditMapper, HsmwAudit> {

	@Autowired
	private HsmwAuditMapper hsmwAuditMapper;
	@Autowired
	private HsmwUserDriverMapper hsmwUserDriverMapper;
	@Autowired
	private HsmwVehicleMapper hsmwVehicleMapper;
	@Autowired
	private CurrentHsmwUserUtils currentHsmwUserUtils;

	@Autowired
	private HsmwVehicleService hsmwVehicleService;

	@Autowired
	private HsmwPointsDetailsService hsmwPointsDetailsService;

	@Autowired
	private HsmwExamineRecordMapper hsmwExamineRecordMapper;

	@Autowired
	private HsmwDriverUserMapper hsmwDriverUserMapper;


	@Autowired
	private HsmwDriverNewsService hsmwDriverNewsService;




	@Value(value = "${sms.appKey}")
	private String appKey;
	@Value(value = "${sms.channel}")
	private String channel;
	@Value(value = "${sms.smsSign}")
	private String smsSign;
	@Value(value = "${sms.appId}")
	private int appId;
	@Value(value = "${sms.auditNotice}")
	private int auditSmsTemplateId;


	public IPage<HsmwAudit> getHsmwAuditPage(IPage page, HsmwAudit hsmwAudit) {
		LambdaQueryWrapper<HsmwAudit> queryWrapper = new LambdaQueryWrapper<>();
		//查询时间
		if (!StrUtil.isBlank(hsmwAudit.getQueryParam())) {
			queryWrapper.like(HsmwAudit::getName, hsmwAudit.getQueryParam()).or().like(HsmwAudit::getUsername,hsmwAudit.getQueryParam());
		}
		LocalDateTime createTime = hsmwAudit.getCreateTime();
		if (null!=(hsmwAudit.getCreateTime())) {
			LocalDateTime tomDay = createTime.plusDays(1L);
			queryWrapper.gt(HsmwAudit::getCreateTime, hsmwAudit.getCreateTime()).lt(HsmwAudit::getCreateTime,tomDay);
		}
		if (!StrUtil.isBlank(hsmwAudit.getAuditStatus()) && hsmwAudit.getAuditStatus().equals(CommonConstants.AUDIT_ING)) {
			queryWrapper.eq(HsmwAudit::getAuditStatus, hsmwAudit.getAuditStatus());
		} else if (StrUtil.isBlank(hsmwAudit.getAuditStatus())) {
			queryWrapper.in(HsmwAudit::getAuditStatus, Arrays.asList(CommonConstants.AUDIT_COMPLETE, CommonConstants.AUDIT_FAILURE));
		} else {
			queryWrapper.eq(HsmwAudit::getAuditStatus, hsmwAudit.getAuditStatus());
		}
		queryWrapper.orderByDesc(HsmwAudit::getCreateTime);
		IPage ipage = this.baseMapper.selectPage(page, queryWrapper.orderByDesc(HsmwAudit::getCreateTime));
		return ipage;
	}

	public HsmwAudit getHsmwAuditById(String id) {
		LambdaQueryWrapper<HsmwAudit> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(HsmwAudit::getId, id);
		return hsmwAuditMapper.selectOne(queryWrapper);
	}

	/**
	 * 新增或修改 逻辑删除
	 *
	 * @return
	 */
	public DataResponse saveOrUpdateHsmwAudit(HsmwAudit hsmwAudit) {
		StringBuffer msgs = new StringBuffer();
		Integer result = 0;
		if (StringUtils.isNotBlank(hsmwAudit.getId())) {
			//hsmwAudit.setAuditStatus(CommonConstants.AUDIT_ING);
			result = hsmwAuditMapper.updateById(hsmwAudit);
			if("".equals(hsmwAudit.getAuditStatus())){
				hsmwAudit.setAuditStatus(null);
			}
			/*if(StringUtils.equals("审核中",hsmwAudit.getAuditStatus())){
				String msg = "司机";
				SendSmsUtil.sendBizOrderSmsCode(appId, appKey, msg,auditSmsTemplateId, smsSign, "13520391225");
				SendSmsUtil.sendBizOrderSmsCode(appId, appKey, msg,auditSmsTemplateId, smsSign, "18500200183");
				SendSmsUtil.sendBizOrderSmsCode(appId, appKey, msg,auditSmsTemplateId, smsSign, "18711909999");

			}*/
			msgs.append("修改成功");
		} else {
			LoginUser currentUser = currentHsmwUserUtils.getCurrentUserInfo();
			hsmwAudit.setFlag(0);
			String  auditId = CommonUtils.generateId(hsmwAudit);
			//hsmwAudit.setAuditStatus(CommonConstants.AUDIT_ING);
			hsmwAudit.setId(auditId);
			result = hsmwAuditMapper.insert(hsmwAudit);
			HsmwExamineRecord record = new HsmwExamineRecord();
			record.setAuditId(auditId);
			record.setAuditType(ExamineTypeEnum.TYPE_DRIVER.getValue());
			record.setName(hsmwAudit.getName());
			record.setUserId(currentUser.getId());
			record.setUsername(hsmwAudit.getUsername());
			record.setMessage("有用户申请成为司机并绑定"+hsmwAudit.getVehiclePlate());
			hsmwExamineRecordMapper.insert(record);


			msgs.append("添加成功");
		}
		return new DataResponse(result != 0 ? CommonConstants.ResponseStatus.SUCCESS :  CommonConstants.ResponseStatus.FAIL, msgs.toString());
	}


	public DataResponse passHsmwAudit(String id) {
		HsmwAudit hsmwAudit = this.getById(id);
		hsmwAudit.setAuditTime(LocalDateTime.now());
		LoginUser currentUser = currentHsmwUserUtils.getCurrentUserInfo();
		hsmwAudit.setAuditId(currentUser.getId());
		hsmwAudit.setAuditName(currentUser.getName());
		hsmwAudit.setAuditStatus(CommonConstants.AUDIT_COMPLETE);
		List<HsmwVehicle> vehicles =null;
		HsmwVehicle vehicle = new HsmwVehicle();
		HsmwAudit audit = hsmwAuditMapper.selectById(id);
		List<HsmwUserDriver> userDrivers = hsmwUserDriverMapper.selectList(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getIdCard, hsmwAudit.getIdCard()));
		if(CollectionUtil.isNotEmpty(userDrivers)){
			return new DataResponse( CommonConstants.ResponseStatus.FAIL,"身份证号码重复");
		}

		if(StringUtils.isNotBlank(audit.getVehiclePlate())){
			vehicles = hsmwVehicleService.list(new LambdaQueryWrapper<HsmwVehicle>()
					 .eq(HsmwVehicle::getVehiclePlate,audit.getVehiclePlate()));
			 if(CollectionUtil.isNotEmpty(vehicles)){
				 vehicle=vehicles.get(0);
				 Integer count = hsmwUserDriverMapper.selectCount(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getVehicleId, vehicle.getId()));
				 if(count >= Integer.valueOf(vehicle.getMaxDriverNumber())){
					 return  DataResponse.failure(CommonConstants.ResponseStatus.VALIDATE_FAILED.getCode(),"绑定司机超出限制，请更换！");
				 }
				 //新建司机
				 HsmwUserDriver hsmwUserDriver = new HsmwUserDriver();
				 BeanUtil.copyProperties(hsmwAudit, hsmwUserDriver, "id");
				 hsmwUserDriver.setWorkStatus(CommonConstants.DRIVER_FREE);
				 hsmwUserDriver.setVehicleId(vehicle.getId());
				 hsmwUserDriver.setMyPicture(audit.getMyPicture());
				 hsmwUserDriver.setScore("600");
				 hsmwUserDriver.setOwnCompanyId(vehicle.getLeasingCompanyId());
				 hsmwUserDriver.setOwnCompanyName(vehicle.getLeasingCompanyName());
				 hsmwUserDriverMapper.insert(hsmwUserDriver);
				 HsmwDriverUser user = hsmwDriverUserMapper.selectById(audit.getUserId());
				 user.setName(audit.getName());
				 user.setAvatar(audit.getMyPicture());
				 user.setType(UserTypeEnum.DRIVER.getValue());
				 hsmwDriverUserMapper.updateById(user);
				 this.updateById(hsmwAudit);
				 HsmwPointsDetails hsmwPointsDetails = new HsmwPointsDetails();
				 hsmwPointsDetails.setType("司机认证");
				 hsmwPointsDetails.setDriverId(hsmwUserDriver.getId());
				 hsmwPointsDetails.setTypeIntegral(new BigDecimal(10));
				 hsmwPointsDetailsService.save(hsmwPointsDetails);
				 String msg = "您的司机认证已通过，请知晓！";
				 TencentPushUtils.pushMsg(msg,user.getUsername(),"has_new_message");
				 HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
				 hsmwDriverNews.setAlreadyRead("0");
				 hsmwDriverNews.setMessage(msg);
				 hsmwDriverNews.setUserId(user.getId());
				 hsmwDriverNewsService.save(hsmwDriverNews);

				 return  new DataResponse();
			 }else {
			 	return  DataResponse.failure(CommonConstants.ResponseStatus.VALIDATE_FAILED.getCode(),"您输入的车牌号不存在，请检查后重新输入！");
			 }
		}else {
			return  DataResponse.failure(CommonConstants.ResponseStatus.VALIDATE_FAILED.getCode(),"您输入的车牌号为空，请检查后重新输入！");
		}
	}

	public void refuseHsmwAudit(String id, String remark) {
		HsmwAudit hsmwAudit = this.getById(id);
		hsmwAudit.setAuditStatus(CommonConstants.AUDIT_FAILURE);
		hsmwAudit.setAuditId(currentHsmwUserUtils.getCurrentUserInfo().getId());
		hsmwAudit.setAuditName(currentHsmwUserUtils.getCurrentUserInfo().getName());
		hsmwAudit.setAuditTime(LocalDateTime.now());
		hsmwAudit.setRemark(remark);
		this.updateById(hsmwAudit);

		if(StringUtils.isNotBlank(hsmwAudit.getUserId())){
			HsmwDriverUser hsmwDriverUser = hsmwDriverUserMapper.selectById(hsmwAudit.getUserId());
			if(StringUtils.isNotNull(hsmwDriverUser)){
				String msg = "您的司机认证因为："+remark+"，暂未通过，请重新提交认证！";
				TencentPushUtils.pushMsg(msg,hsmwDriverUser.getUsername(),"has_new_message");
				HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
				hsmwDriverNews.setAlreadyRead("0");
				hsmwDriverNews.setMessage(msg);
				hsmwDriverNews.setUserId(hsmwDriverUser.getId());
				hsmwDriverNewsService.save(hsmwDriverNews);
			}
		}
	}
}
